// 获取应用实例
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    actionType: '新增',
    modelid: '',
    model: {
      Pictures: [],
      Detail: []
    },
    maxFiles: 3,
    files: [],
    showPJ: false, // 显示选择配件
    items: [],
    pageIndex: 0,
    pageSize: 15,
    activeId: 1,
    mainActiveIndex: 0,
    value: '',
    showAction: false,
  },
  onLoad: function (options) {
    let _this = this;
    let _id = options.id || '';
    _this.loadDetail(_id);
    _this.setData({
      modelid: _id,
      actionType: (_id ? "修改" : "新增")
    });
  },
  loadDetail(id) {
    let _this = this;
    const _user = wx.getStorageSync(app.cache.AUTH_USER);
    app.ajax({
      url: 'StockIn/View',
      data: {
        customerId: _user.Id,
        inId: id,
      },
      success(resp) {
        if (resp.model) {
          _this.setData({
            modelid: resp.model.Id,
            model: resp.model
          });
        }
      }
    });
  },
  bindPickerChange(e) {
    this.setData({
      zrcd: e.detail.value
    });
  },
  addImage(e) {
    let _this = this;
    wx.chooseImage({
      sizeType: ['compressed' /*'original','compressed'*/ ], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        let _files = _this.data.files;
        if (res.tempFilePaths.length + _files.length > _this.data.maxFiles) {
          wx.showToast({
            icon: 'none',
            title: `最多允许上传${_this.data.maxFiles}张图片`
          });
          return;
        }
        let startIdx = _files.length;
        for (let i = 0; i < res.tempFilePaths.length; i++) {
          _files.push({
            img: res.tempFilePaths[i],
            percent: 0,
            id: 0,
            unique: startIdx + i
          });
        }
        _this.setData({
          files: _files
        }, function () {
          for (let j = 0; j < res.tempFilePaths.length; j++) {
            _this.uploadFile(res.tempFilePaths[j], startIdx + j);
          }
        });
      }
    });
  },
  uploadFile(file, idx) {
    let _this = this;
    var task = wx.uploadFile({
      url: `${app.apiRoot}/Picture/AsyncUpload`,
      filePath: file,
      name: 'qqfile',
      success(resp) {
        var data = JSON.parse(resp.data) //返回的是[字符串]，需要自己转为JSON格式
        let _files = _this.data.files;
        _files[idx].id = data.pictureId;
        _this.setData({
          files: _files
        });
      },
      fail(resp) {
        console.log('fail', resp);
      }
    });

    task.onProgressUpdate((res) => {
      let _files = _this.data.files;
      _files[idx].percent = res.progress;
      _this.setData({
        files: _files
      });
    });
  },
  tapImg(e) {
    let _this = this;
    let _idx = e.currentTarget.dataset.idx
    wx.previewImage({
      urls: _this.data.model.Pictures,
      current: _this.data.model.Pictures[_idx]
    });
  },
  showPopupPJ() {
    this.loadEquipments(0);
    this.setData({
      showPJ: true
    });
  },
  onClose() {
    this.setData({
      showPJ: false,
    });
  },


  onClickNav({
    detail = {}
  }) {
    this.setData({
      mainActiveIndex: detail.index || 0
    });
  },

  onClickItem({
    detail = {}
  }) {
    const activeId = this.data.activeId === detail.id ? null : detail.id;
    this.setData({
      activeId
    });
  },
  doSave(e) {
    let _this = this;
    const _user = wx.getStorageSync(app.cache.AUTH_USER);
    let _imgs = '';
    let _picDone = true;
    for (let i = 0; i < _this.data.files.length; i++) {
      if (_this.data.files[i].id <= 0) {
        _picDone = false;
        break;
      } else {
        _imgs += ',' + _this.data.files[i].id;
      }
    }
    if (!_picDone) {
      app.showNotify('请等待图片上传完成');
      return;
    }
    const {model}=_this.data;
    model.CustomerId = _user.Id;
    model.SelectedPictureIds = _imgs;
    if(model.MaintenanceId<=0)
    {
      app.showNotify('维修Id未找到');
        return;
    }
    app.ajax({
      url: 'StockIn/Save',
      data: model,
      timeout: 2000,
      again: false, // 重复调用
      verifyToken: true,
      success: function (resp) {
        if (!resp.result) {
          app.showNotify(resp.msg);
        } else {
          wx.showToast({
            title: _this.data.actionType + '成功',
            complete() {
              wx.navigateBack({
                delta: 1
              });
            }
          });
        }
      }
    });
  },
  goApprove(e) {
    let _this = this;
    const pass = e.target.dataset.pass === '1';
    const _user = wx.getStorageSync(app.cache.AUTH_USER);
    app.ajax({
      url: 'StockIn/Audit',
      data: {
        inId: _this.data.model.Id,
        customerId: _user.Id,
        pass,
      },
      success: function (resp) {
        if (!resp.result) {
          app.showNotify(resp.msg)
          return;
        } else {
          if (resp.id > 0) {
            wx.request({
              url: `${app.apiRoot}/StockIn/SubscribeMessage`,
              method: 'POST',
              data: {
                id: resp.id,
                templateId: 'nQpdDl04GLhjY7EwrF3rk6orDUEI_WcDQ3lp5FUg09k'
              },
              header: {
                'content-type': 'application/x-www-form-urlencoded'
              },
              success(msgRes) {
                console.log(msgRes.data);
              }
            })
          }
          wx.showToast({
            title: '操作成功',
            complete() {
              wx.navigateBack({
                delta: 1
              });
            }
          });
        }
      },
      fail(resp) {
        console.log('fail', resp);
      }
    });
  },
  goIn(e) {
    let _this = this;
    const pass = e.target.dataset.pass === '2';
    const _user = wx.getStorageSync(app.cache.AUTH_USER);
    app.ajax({
      url: 'StockIn/In',
      data: {
        inId: _this.data.model.Id,
        customerId: _user.Id,
        pass,
      },
      success: function (resp) {
        if (!resp.result) {
          app.showNotify(resp.msg)
          return;
        } else {
          if (resp.id > 0) {
            wx.request({
              url: `${app.apiRoot}/StockIn/RemindMessage`,
              method: 'POST',
              data: {
                id: resp.id,
                templateId: 'nQpdDl04GLhjY7EwrF3rk6orDUEI_WcDQ3lp5FUg09k'
              },
              header: {
                'content-type': 'application/x-www-form-urlencoded'
              },
              success(msgRes) {
                console.log(msgRes.data);
              }
            })
          }
          wx.showToast({
            title: '操作成功',
            complete() {
              wx.navigateBack({
                delta: 1
              });
            }
          });
        }
      },
      fail(resp) {
        console.log('fail', resp);
      }
    });
  },
  doBack(e) {
    wx.navigateBack({
      delta: 1
    });
  },
  onSearch({
    detail
  }) {
    this.setData({
      value: detail,
      pageIndex: 0,
    })
    this.loadEquipments();
  },
  onFocus() {
    this.setData({
      showAction: true
    });
  },
  onCancel() {
    this.setData({
      showAction: false,
      value: '',
      pageIndex: 0,
    });
    this.loadEquipments();
  },
  onStepperChange(e) {
    const _this = this;
    const {
      model,
      items
    } = _this.data;

    const {
      currentTarget: {
        dataset: {
          id
        }
      },
      detail
    } = e;
    const d = model.Detail.filter(m => m.EquipmentId === id)[0];
    if (d) {
      d.Amount = detail;
    } else {
      const equipment = items.filter(m=>m.Id===id)[0];
      if(equipment)
      {
        model.Detail.push({
          Id: 0,
          EquipmentId: id,
          Title:equipment.Title,
          Label:equipment.Label,
          Amount: detail
        });
      }
    }
    _this.setData({
      model
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})